﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KBVault.DAL.Repository;
using NLog;
using KBVault.DAL.Entities;
using KBVault.Web.Infrastructure;
using KBVault.DAL.Exceptions;
using System.IO;

namespace KBVault.Web.Application.UC.Articles
{
    public partial class NewArticle : KBVaultBaseUserControl
    {
        public string ArticleHashKey
        {
            get
            {
                return (ViewState["ArticleHashKey"] != null) ? ViewState["ArticleHashKey"].ToString() : String.Empty;
            }
            set
            {
                ViewState["ArticleHashKey"] = value;
            }
        }
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                uploadButtonContainer.Visible = false;
                ArticleHashKey = Guid.NewGuid().ToString();
                panelTitle.InnerText = "Add New Article";
                ddlCategory.DataSource = CategoryRepository.List();
                ddlCategory.DataTextField = "Name";
                ddlCategory.DataValueField = "Id";
                try
                {
                    if ((this.Page as KBVaultAdminPage).ActiveCategoryId > 0)
                        ddlCategory.SelectedValue = (this.Page as KBVaultAdminPage).ActiveCategoryId.ToString();
                }
                catch (Exception ex)
                {
                    Log.Error(ex.Message);
                }
                ddlCategory.DataBind();
                publishStartDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                publishEndDate.Text =  DateTime.Now.AddYears(5).ToString("dd/MM/yyyy");
                int articleId = (this.Page as KBVaultAdminPage).ActiveArticleId;
                if (articleId > 0)
                {
                    try
                    {
                        Article a = ArticleRepository.Get(articleId);
                        ddlCategory.SelectedValue = ddlCategory.Items.FindByValue(a.CategoryId.ToString()).Value;
                        txtTitle.Text = a.Title;
                        txtContent.Text = Server.HtmlDecode(a.Content);
                        panelTitle.InnerText = "Edit Article";
                        backToCategory.NavigateUrl = "~/Application/ArticleOps.aspx?op=list&Category=" + a.CategoryId;
                        chkDraft.Checked = a.IsDraft == 1;
                        publishStartDate.Text = a.PublishStartDate.ToString("dd/MM/yyyy");
                        publishEndDate.Text = a.PublishEndDate.ToString("dd/MM/yyyy");
                        txtMetaDescription.Text = a.MetaDescription;
                        txtTags.Text = String.Join(",", a.Tags.Select(t => t.Name).ToArray<string>());
                        rptAttachments.DataSource = a.Attachments;
                        rptAttachments.DataBind();
                        attachmentContainer.Visible = true;
                        uploadButtonContainer.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                        ShowExceptionMessage();
                    }
                }
                
                
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Article a = new Article()
                {
                    CategoryId = Convert.ToInt32( ddlCategory.SelectedItem.Value),
                    Content = txtContent.Text,
                    Title = txtTitle.Text,                    
                    IsDraft = (chkDraft.Checked ? 1 : 0 ),
                    Edited = DateTime.Now,
                    MetaDescription = txtMetaDescription.Text
                };
                // Tags
                string[] tags = txtTags.Text.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string tag in tags)
                {
                    try
                    {
                        a.Tags.Add(TagRepository.GetByName(tag));
                    }
                    catch (NoDataFoundException)
                    {
                        // add tag if not exists
                        Tag t = new Tag(){ Name = tag };
                        TagRepository.Create(ref t);
                        a.Tags.Add(t);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                    }
                }
                if (!String.IsNullOrEmpty(publishStartDate.Text))
                {
                    a.PublishStartDate = Convert.ToDateTime(publishStartDate.Text);
                }
                if (!String.IsNullOrEmpty(publishEndDate.Text))
                {
                    a.PublishEndDate = Convert.ToDateTime(publishEndDate.Text);
                }
                if ((this.Page as KBVaultAdminPage).ActiveArticleId > 0)
                {
                    a.Id = (this.Page as KBVaultAdminPage).ActiveArticleId;
                    if( ArticleRepository.Get(a.Id) != null )
                        ArticleRepository.Update(a);                    
                }
                else
                {
                    a.Created = DateTime.Now;
                    ArticleRepository.Create(ref a);
                }
                //Update attachments based on hashkey
                AttachmentRepository.UpdateArticleIdByHash(a.Id, ArticleHashKey);
                if (!String.IsNullOrEmpty((this.Page as KBVaultAdminPage).ReturnUrl))
                    Response.Redirect((this.Page as KBVaultAdminPage).ReturnUrl);
                else
                    Response.Redirect("~/Application/ArticleOps.aspx?Op=List&Category=" + a.CategoryId.ToString());
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                ShowExceptionMessage();
            }
        }

        protected void rptAttachments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Remove")
                {
                    int Id = Convert.ToInt32(e.CommandArgument);
                    Attachment a = AttachmentRepository.Get(Id);
                    AttachmentRepository.Delete(Id);
                    File.Delete(Server.MapPath(a.Path + "/" + a.Id + "." + a.Extension));
                    rptAttachments.DataSource = ArticleRepository.Get((this.Page as KBVaultAdminPage).ActiveArticleId).Attachments;
                    rptAttachments.DataBind();

                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                ShowExceptionMessage();
            }
        }
    }
}